<template>
  <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('km.editCataInformation')" :visible.sync="dialogEditFormVisible" width="50%" @close="close">
    <el-form label-position="top"
             :model="formStacked"
             ref="formStacked"
             size="small"
             :rules="rules">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('km.catalogueBelongTo')">
            <el-select size="mini"
                       v-model="formStacked.type"
                       style="width: 100%"
                       :placeholder="$t('km.viewCategory')">
              <el-option
                v-for="item in typeOptions"
                :label="item.n"
                :value="item.k"
                :key="item.k"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('km.catalogueName')" prop="name">
            <el-input size="mini" v-model.trim="formStacked.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('km.cataSort')" prop="order">
            <el-input size="mini" v-model.trim.number="formStacked.order" class="sort"></el-input>
            <span class="sort-description">{{$t('km.sortDescription')}}</span>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="flag === 'kf'">
          <operate-dep ref="dep"
                       :show-department="formStacked.showDepartment || []"
                       :show-agents="formStacked.showAgents || []"
                       style="margin-top: -10px"
                       v-show="kmType === 'inner'"></operate-dep>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click.stop="dialogEditFormVisible = false" class="primary_btn">{{$t('public.cancel')}}</el-button>
      <el-button type="primary" @click="editCatalog" class="primary_btn">{{$t('public.confirm')}}</el-button>
    </div>
  </el-dialog>
</template>
<script>
  import {checkform} from '@/utils/validate.js'
  import operateDep from './operateDep'
  export default {
    name: 'EditCatalogue',
    props: {
      model: Object,
      kmType: String
    },
    data () {
      var validateNumber = (rule, value, callback) => {
        let match = checkform(value, 'Number3')
        if (match) {
          callback(new Error(this.$t(match)))
        } else {
          callback()
        }
      }
      let validateLength = (rule, value, callback) => {
        if (value.length > 25) {
          callback(new Error(this.$t('km.catalogueNameTooLong')))
        } else {
          callback()
        }
      }
      return {
        flag: this.$store.getters.isEcommerce ? 'ecommerce' : 'kf',
        dialogEditFormVisible: false,
        formStacked: {
          _id: this.model._id,
          name: this.model.name,
          order: this.model.order,
          showDepartment: this.model.showDepartment || [],
          showAgents:this.model.showAgents||[],
          type: this.model.pid
        },
        formLabelWidth: '120px',
        isShowSleect: false,
        rules: {
          order: [
            {required: true, message: this.$t('validate.required')},
            {required: true, validator: validateNumber, trigger: 'blur'}
          ],
          name: [
            {required: true, message: this.$t('validate.required')},
            {validator: validateLength, trigger: 'blur'}
          ]
        },
        curCata: {}, // 当前目录信息
        toLeavel: 0, // 目标目录层级
        typeOptions: [] // 目录select
      }
    },
    computed: {
    },
    components: {
      operateDep
    },
    methods: {
      treeOptions: function () {
        // console.dir(this.model)
        // let tree = this.model.childs
        let catalogTree = this.$store.state.km.catalogTree || []
        let tree = [{
          name: this.$t('km.catalogLook'),
          childs: catalogTree,
          _id: '0'
        }]
        let options = []
        let self = this
//        手动重新整理目录结构  只展示前三层目录
        if (this.kmType === 'inner') {
          for (let i = 0; i < tree.length; i++) {
            if (tree[i]._id === self.model._id) {
              continue
            }
            let obj = {k: tree[i]._id, n: tree[i].name}
            options.push(obj)
            if (tree[i].childs && tree[i].childs.length > 0) {
              for (let j = 0; j < tree[i].childs.length; j++) {
                if (tree[i].childs[j]._id === self.model._id) {
                  // 当前树的子树不push导option中，应该当前树不能移到子树中
                  continue
                }
                let obj = {k: tree[i].childs[j]._id, n: '·' + tree[i].childs[j].name}
                options.push(obj)
                if (tree[i].childs[j].childs && tree[i].childs[j].childs.length > 0) {
                  for (let k = 0; k < tree[i].childs[j].childs.length; k++) {
                    if (tree[i].childs[j].childs[k]._id === self.model._id) {
                      continue
                    }
                    let obj = {k: tree[i].childs[j].childs[k]._id, n: '··' + tree[i].childs[j].childs[k].name}
                    options.push(obj)
                  }
                }
              }
            }
          }
        }
//        let getTree = function (_childs) {
//          for (let i = 0; i < _childs.length; i++) {
//            let t = _childs[i]
//            if (t._id === self.model._id) {
//              continue
//            }
//            let obj = {k: t._id, n: t.name}
//            options.push(obj)
//            if (t.childs && t.childs.length > 0) {
//              getTree(t.childs)
//            }
//          }
//        }
//        getTree(tree)
        if (this.kmType === 'outer') {
          options = [{k: tree[0]._id, n: tree[0].name}]
        }
        return options
      },
      open () {
        this.formStacked = {
          _id: this.model._id,
          name: this.model.name,
          order: this.model.order,
          showDepartment: this.model.showDepartment || [],
          showAgents:this.model.showAgents || [],
          type: this.model.pid
        }
        console.log(this.model);
        this.typeOptions = this.treeOptions()
        this.dialogEditFormVisible = true
        this.$nextTick(() => {
          this.kmType === 'inner' && this.$refs.dep.setCheckedKeys(this.formStacked.showDepartment)
        })
      },
      close () {
      },
      editCatalog () {
        this.$refs.formStacked.validate((valid) => {
          if (valid) {
            if (this.formStacked.type !== this.model.pid) {
              let curLeavel = this.cataLeavel(this.model, 1)
              console.log(curLeavel)
              let that = this
              that.toLeavel = 0
              let num = 0
              this.$store.state.km.catalogTree.forEach((item) => {
                if (item._id === that.formStacked.type) {
                  that.toLeavel = 1
                } else {
                  let arr = item.childs || []
                  num = that.toCataLeavel(arr, that.formStacked.type, 1)
                }
              })
              if (num && !that.toLeavel) {
                that.toLeavel = num
              }
              if (curLeavel + that.toLeavel > 3) {
                this.$message.error(this.$t('km.overlayers'))
                return
              }
            }
            if (this.kmType === 'inner') {
              this.formStacked.showDepartment = this.$refs.dep.showSelected()[1]
              this.formStacked.showAgents = this.$refs.dep.showSelected()[0]
            }
            this.dialogEditFormVisible = false
            this.$emit('updateCatalog', this.formStacked)
          } else {
          }
        })
      },
      toCataLeavel (dataArr, _id, num) {
        let numNew = num
        let reNum = 0
        let that = this
        if (dataArr.length) {
          numNew += 1
        }
        dataArr.forEach((item) => {
          if (item._id === _id) {
            that.toLeavel = numNew
          } else {
            let arr = item.childs || []
            reNum = that.toCataLeavel(arr, _id, numNew)
          }
        })
        return reNum
      },
      cataLeavel (data, num) {
        let numNew = num
        if (data.childs && data.childs.length) {
          let that = this
          numNew += 1
          data.childs.forEach((item) => {
            numNew = that.cataLeavel(item, numNew)
          })
        }
        if (numNew > 3) {
          numNew = 3
        }
        return numNew
      }
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl";
  .sort-description
    font-size: 12px
    color: $c-prompt
  .editCataForm
    display inline
    padding-right 5px
    .icon-beizhu
      padding 0px 6px
  .sort
    width 100%
    float left
    margin-top 2px
</style>

